<template>
  <div>
    <div class="confirmInfo_title gl_clear">
      <span class="gl_fl">选择教练、领队</span>
      <el-button v-if="currentUserType === 'Delegation'" style="margin-top: 2px" class="gl_fr" type="primary" size="mini" @click="clickAddOfficial">添加人员</el-button>
      <el-button v-if="currentUserType === 'Personal'" style="margin-top: 2px" class="gl_fr" type="primary" size="mini" @click="clickChooseOfficial">选择人员</el-button>
    </div>
    <div v-loading="loading" class="gameEntry_shadow">
      <template v-for="(item, index) in MemberDataForm">
        <div v-show="item.children.length" :key="index" class="member_list_group">
          <div class="member_type_title">{{ item.title }}</div>
          <ul class="member_list">
            <li v-for="(jtem, jndex) in item.children" :key="jndex" class="member_item" @click="chooseMember(jtem, jndex, index)">
              <div class="member_face" :class="(jtem.isActive&&officialData.map(res=>{return res.officialId}).includes(jtem.id)) ? 'active' : ''">
                <img class="member_face_img" :src="getStaticFileUrl(jtem.imagePath)" :onerror="errorPhoto()" alt="">
                <i class="el-icon-success choose_member_icon" />
              </div>
              <div class="member_name gl_ellipsis" :class="(jtem.isActive&&officialData.map(res=>{return res.officialId}).includes(jtem.id)) ? 'active' : ''" :title="jtem.name">{{ jtem.name }}</div>
            </li>
            <li v-if="!item.children.length" class="noConfirmInfo">
              暂无该角色人员可以选择
            </li>
          </ul>
        </div>
      </template>
      <div v-if="!hasOfficial" class="noConfirmInfo">
        暂无人员可以选择。
      </div>
    </div>
    <el-row class="control_row">
      <el-col :span="24" align="center">
        <el-button type="default" @click="clickPrevStep()">上一步</el-button>
        <el-button type="primary" :loading="btnLoading" @click="submitOfficial()">下一步</el-button>
      </el-col>
    </el-row>

    <!-- 个人 => 选择人员(裁判、领队)弹窗 -->
    <modal-by-choose-official ref="refModalByChooseOfficial" :dict="dict" :choose-official-loading="chooseOfficialLoading" @onSubmitChooseOfficial="submitChooseOfficial" />

    <!-- 添加人员弹窗 -->
    <el-dialog class="gl_dialog_TitleLine" title="编辑" :visible.sync="dialogVisibleForPersonal" :close-on-click-modal="false" width="1200px">
      <personal-info ref="refPersonalInfo" :user-data="createRegisterInput" :filter-tags="['Athlete']" :is-show-tag="true" :is-prop-data="true" />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" :loading="submitPersonalInfoLoading" @click="dialogVisibleForPersonal = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="submitPersonalInfo">{{ $t('button.submit') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import defaultPhoto from '@/assets/images/face_default.png';
import { deepCopy } from '@/lib';

import {
  api_GET_EventsManagementRegister, // 查询注册列表
  api_POST_EventsManagementRegisterWithtags, // 添加会员 多选标签
  api_GET_EventsManagementRegisterByIdCard,
  api_POST_EventsManagementEntryCompetitionOfficial // 2-2添加教练领队报项（如果已存在报名则可以添加，否则不成功）
} from '@/extend/api/gameswaggerApi/app';
import { api_GET_EventsManagementEntryNotinentrywhite } from '@/extend/api/whilteListApi/api'
import {
  SiSTKWEventsManagementCreateRegisterWithTagsInput
} from '@/lib/form/game/swaggerForm';

import { MemberDataForm } from '@/lib/form/home/enter/member';

import PersonalInfo from '@/components/PersonalInfo';
import ModalByChooseOfficial from './modalByChooseOfficial';
import { CopyData } from '@/lib';

export default {
  components: {
    PersonalInfo,
    ModalByChooseOfficial
  },
  props: {
    // 当前用户信息
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    // 当前用户信息
    userTeamInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    },
    isShow: {
      type: Boolean
    },
    // 字典信息
    dict: {
      type: Object,
      default () {
        return {};
      }
    },
    // 字典信息
    district: {
      type: Array,
      default () {
        return [];
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    // 通过点击个人或团体传进来的状态
    currentUserType: {
      type: String,
      default: ''
    },
    attachOfficial: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data () {
    return {
      loading: false,
      btnLoading: false,
      defaultPhoto: defaultPhoto,
      MemberDataForm: new MemberDataForm(),
      personList: [], // 获取到的人员数据
      activePersonData: {},
      officialData: [], // 传递出去的官员数据
      chooseOfficialLoading: false,
      dialogVisibleForPersonal: false, // 添加人员弹窗显示隐藏
      submitPersonalInfoLoading: false,
      createRegisterInput: new SiSTKWEventsManagementCreateRegisterWithTagsInput() // 添加人员vo
    };
  },
  computed: {
    hasOfficial () {
      for (const k in this.MemberDataForm) {
        const ktem = this.MemberDataForm[k];
        if (ktem.children.length) {
          return true;
        }
      }
      return false;
    }
  },
  watch: {
    isShow: {
      immediate: true,
      deep: true,
      handler: function(val) {
        if (val) {
          this.activePersonData = {};
          this.officialData = [];
          this.personList = [];
          this.$emit('onChangeOfficialData', this.officialData);
          this.api_GET_EventsManagementRegister();
        }
      }
    },
    dialogVisibleForPersonal(val) {
      if (!val) {
        this.$refs.refPersonalInfo.clearInsideUserData();
        this.createRegisterInput = new SiSTKWEventsManagementCreateRegisterWithTagsInput();
      }
    }
  },
  methods: {
    // 点击选择人员按钮
    clickChooseOfficial () {
      this.$refs.refModalByChooseOfficial.open();
    },
    // 点击添加人员按钮
    clickAddOfficial () {
      this.dialogVisibleForPersonal = true;
    },
    // 查询注册列表
    api_GET_EventsManagementRegister() {
      // 如果 requiredIdData.delegationId 为 null 表示这个人没有加入团体，需先加入一个团体
      if (this.requiredIdData.delegationId) {
        this.loading = true;
        api_GET_EventsManagementRegister({ DelegationId: this.requiredIdData.delegationId, IncludeTags: true })
          .then(
            res => {
              this.personList = res.items;
              this.formatOfficialList();
              this.loading = false;
            }
          )
          .catch(
            error => {
              console.log(error);
              this.$message({ type: 'error', message: '查询注册列表失败' });
            }
          );
      } else {
        this.formatOfficialList();
      }
    },
    // 将获取到和现有的教练领队数据处理为页面需要的数据
    formatOfficialList () {
      this.MemberDataForm = new MemberDataForm();
      let dataList = deepCopy(this.personList);

      // 将获取到的官员列表以ID为KEY处理成对象，方便去重
      const _dataListMap = {};
      dataList.forEach(item => {
        _dataListMap[item.id] = item;
      });

      // 如果时非团体报名，那么需要关联已有的附加官员列表
      if (this.currentUserType !== 'Delegation') {
        const _concatList = [];
        // 附加的官员列表与获取到的官员列表做匹配，进行去重，以获取到的为主
        this.attachOfficial.forEach(item => {
          if (!(item.id in _dataListMap)) {
            _concatList.push(item);
          }
        });
        dataList = dataList.concat(_concatList);
      }

      if (dataList.length > 0) {
        // 聚合数据前提取共同的属性
        dataList.forEach(item => {
          for (const k in item.registerTags) {
            const ktem = item.registerTags[k];
            const _key = ktem.registerTagTypeCode;
            if (_key in this.MemberDataForm) {
              const deepItem = deepCopy(item);
              this.MemberDataForm[_key].children.push(deepItem);
            }
          }
        });
      }
    },
    // 提交个人信息
    submitPersonalInfo() {
      this.$refs.refPersonalInfo.getInsideUserData()
        .then(
          res => {
            CopyData(res, this.createRegisterInput);
            this.createRegisterInput.registerTypeCode = 'I';
            this.createRegisterInput.isCurrentUser = false;
            this.createRegisterInput.joinCurrentDelegation = true;
            this.apiRegisterWithTags();
          }
        );
    },
    apiRegisterWithTags () {
      this.submitPersonalInfoLoading = true;
      api_POST_EventsManagementRegisterWithtags(this.createRegisterInput)
        .then(
          res => {
            this.submitPersonalInfoLoading = false;
            this.api_GET_EventsManagementRegister();
            this.$message({
              message: `添加成功`,
              type: 'success',
              showClose: true
            });
            this.dialogVisibleForPersonal = false;
          }
        )
        .catch(
          error => {
            this.submitPersonalInfoLoading = false;
            this.$message({
              message: `添加失败 ${error.error.message}`,
              type: 'warning',
              showClose: true
            });
          }
        );
    },
    // 确认选择教练或领队
    submitChooseOfficial (queryData) {
      this.chooseOfficialLoading = true;
      api_GET_EventsManagementRegisterByIdCard({
        idCardCode: queryData.idCardTypeCode,
        idCardNumber: queryData.idCardNumber,
        name: queryData.name,
        IncludeTags: true
      })
        .then(
          res => {
            const _tagList = res.registerTags;
            const _tagData = _tagList.find(item => item.registerTagTypeCode === queryData.registerTagTypeCode);
            if (_tagData) {
              res.registerTags = [_tagData];
              this.$emit('onAddAttachOfficial', res);
              this.api_GET_EventsManagementRegister();
              this.$refs.refModalByChooseOfficial.close();
            } else {
              this.$message({
                message: `【${queryData.name}】无【${queryData.registerTagTypeName}】身份，请检查信息填写是否准确`,
                type: 'warning',
                showClose: true
              });
            }
            this.chooseOfficialLoading = false;
          }
        )
        .catch(
          error => {
            // 查询失败未找到
            this.$message({
              message: `未查到【${queryData.name}】，请检查信息填写是否准确`,
              type: 'warning',
              showClose: true
            });
            this.chooseOfficialLoading = false;
            console.log('submitChooseOfficial -> error', error);
          }
        );
    },
    // 点击选择教练或领队人员
    chooseMember (row, jndex, type) {
      if (row.isActive) {
        for (let i = 0; i < this.officialData.length; i++) {
          const item = this.officialData[i];
          if (item.officialId === row.id && item.officialTagCode === type) {
            this.officialData.splice(i, 1);
            break;
          }
        }
      } else {
        this.officialData.push({
          officialId: row.id,
          officialTagCode: type
        });
      }
      this.$set(row, 'isActive', !row.isActive);
    },
    // 点击执行上一步操作
    clickPrevStep () {
      this.$emit('onPrevStep');
    },
    submitOfficial () {
      if (!this.officialData.length) {
        this.$message({
          message: '请至少选择一名教练或领队',
          type: 'warning',
          showClose: true
        });
        return;
      }

      const _hasCoachOrLeader = this.officialData.find(item => item.officialTagCode === 'Coach' || item.officialTagCode === 'Leader');
      if (_hasCoachOrLeader) {
        let officialIds = []
        this.officialData.map(res => {
          if(res.officialTagCode === 'Leader'|| res.officialTagCode === 'Coach') {
            officialIds.push(res.officialId)
          }
        })
        api_GET_EventsManagementEntryNotinentrywhite(this.gameInfo.id,{'officialIds': officialIds})
        .then(
          res => {
            if(res.length>0) {
              const resId = res.map(nes => {
                return nes.id
              })
              this.officialData = this.officialData.filter(jes=> {
              return !resId.includes(jes.officialId)
            })
              console.log("🚀 ~ file: stepByOfficial.vue:376 ~ submitOfficial ~ this.officialData:", this.MemberDataForm)
            const wgitlepeople = res.map(nes => {
                return nes.name
              })
            this.$message({
             message: `本次赛事限制了教练/领队报名,您选择的${wgitlepeople}不在名单内,请重新选择`,
             type: 'warning',
             showClose: true
            });
            } else {
              this.apiEntryCompetitionOfficial({
               competitionId: this.gameInfo.id,
               delegationId: this.requiredIdData.delegationId,
               registerId: this.requiredIdData.registerId,
               officials: this.officialData
             });
            }
          }
        )
        .catch(
          error => {
            this.btnLoading = false;
            // this.$message({
            //   message: `${error.error.message}`,
            //   type: 'warning',
            //   showClose: true
            // });
          }
        );

      } else {
        this.$message({
          message: '请至少包含一名教练或领队',
          type: 'warning',
          showClose: true
        });
      }
    },
    apiEntryCompetitionOfficial (vo) {
      this.btnLoading = true;
      api_POST_EventsManagementEntryCompetitionOfficial(vo)
        .then(
          res => {
            this.btnLoading = false;
            this.$emit('onChangeOfficialData', this.officialData);
            this.clickNextStep();
          }
        )
        .catch(
          error => {
            this.btnLoading = false;
            this.$message({
              message: `教练或领队提交失败 ${error.error.message}`,
              type: 'warning',
              showClose: true
            });
          }
        );
    },
    // 点击执行下一步操作
    clickNextStep () {
      this.$emit('onNextStep');
    },
    errorPhoto() {
      return 'this.src="' + this.defaultPhoto + '";this.onerror=null;';
    },
    // 获取文件地址
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + '/' + relativeUrl;
    }
  }
};
</script>

<style lang="scss" scoped>
.member_title {
  padding: 20px 0;
  font-size: 20px;
  line-height: 28px;
  color: #353434;
  font-weight: bold;
}
.gameEntry_shadow {
  min-height: 444px;
  padding: 16px 40px;
}
.member_list_group {
  margin-bottom: 30px;
}
.member_type_title {
  padding-bottom: 20px;
  font-size: 14px;
  color: #31456c;
  line-height: 20px;
}
.member_list {
  display: flex;
  flex-wrap: wrap;
  margin-right: -30px;
}
.member_item {
  width: 78px;
  margin-right: 35px;
  margin-bottom: 20px;
  cursor: pointer;
}
.member_face {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px solid #979797;
  margin-bottom: 10px;
  // overflow: hidden;
}
.active.member_face {
  border-color: #1890FF;
}
.member_face_img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  object-position: top;
}
.choose_member_icon {
  display: none;
  position: absolute;
  right: -5px;
  bottom: 0;
  color: #1890FF;
  font-size: 24px;
  background-color: #fff;
  border-radius: 50%;
}
.active .choose_member_icon {
  display: block;
}
.member_name {
  text-align: center;
  color: #353434;
}
.active.member_name {
  color: #1890FF;
}
.noConfirmInfo {
  width: 100%;
  text-align: center;
  padding: 50px 0;
  font-size: 14px;
  text-align: center;
  color: #aaa;
}
.alertBox{
  width: 236px;
  text-align: center;
  vertical-align: middle;
  float: right;
}
</style>
